package com.xuhaowei.mvcframework.servlet;

import com.xuhaowei.mvcframework.myannotation.*;
import com.xuhaowei.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;


import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.net.URL;
import java.util.*;

/**
 * created By Xuhw 2019.10.01
 * congratulation for the china national day
 */


@XUCompoment
public class XUDispatcherServlet extends HttpServlet {

    @XUAutowired
    private TransactionManager transactionManager;

    private Properties contextConfig = new Properties();

    private List<String> className = new ArrayList<String>();

    //IOC容器
    private Map<String, Object> mapping = new HashMap<String, Object>();
    //保存url 和method 的对应关系
    private Map<String, Method> handlerMapping = new HashMap<String, Method>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //派遣，分发任务
        try {
            //委派模式
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Excetion Detail:" + Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath, "").replaceAll("/+", "/");
        if (!this.handlerMapping.containsKey(url)) {
            resp.getWriter().write("404 Not Found!!");
            return;
        }

        Method method = this.handlerMapping.get(url);
        //第一个参数：方法所在的实例
        //第二个参数：调用时所需要的实参
        Map<String, String[]> params = req.getParameterMap();
        //获取方法的形参列表
        Class<?>[] parameterTypes = method.getParameterTypes();
        //保存请求的url参数列表
        Map<String, String[]> parameterMap = req.getParameterMap();
        //保存赋值参数的位置
        Object[] paramValues = new Object[parameterTypes.length];
        //按根据参数位置动态赋值
        for (int i = 0; i < parameterTypes.length; i++) {
            Class parameterType = parameterTypes[i];
            if (parameterType == HttpServletRequest.class) {
                paramValues[i] = req;
                continue;
            } else if (parameterType == HttpServletResponse.class) {
                paramValues[i] = resp;
                continue;
            } else if (parameterType == String.class) {

                //提取方法中加了注解的参数
                Annotation[][] pa = method.getParameterAnnotations();
                for (int j = 0; j < pa.length; j++) {
                    for (Annotation a : pa[i]) {
                        if (a instanceof XURequestParam) {
                            String paramName = ((XURequestParam) a).value();
                            if (!"".equals(paramName.trim())) {
                                String value = Arrays.toString(parameterMap.get(paramName))
                                        .replaceAll("\\[|\\]", "")
                                        .replaceAll("\\s", ",");
                                paramValues[i] = value;
                            }
                        }
                    }
                }

            }
        }
        //投机取巧的方式
        //通过反射拿到method所在class，拿到class之后还是拿到class的名称
        //再调用toLowerFirstCase获得beanName
        String beanName = method.getDeclaringClass().getName();

        method.invoke(mapping.get(beanName), new Object[]{req, resp});
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1、加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        //2、扫描相关的类
        doScanner(contextConfig.getProperty("scanPackage"));
        //3、初始化所有相关的类的实例，并且放入到IOC容器之中
        doInstance();
        //4、完成依赖注入
        doAutowired();
        //针对Service层进行事务处理
//        addTransaction();
        //5、初始化HandlerMapping
        initHandlerMapping();
        //6.
        System.out.println("Xu Spring Framework is init");
    }

    //完成自动的依赖注入
    private void doAutowired() {
        if (mapping.isEmpty())
            return;
        else {
            for (Map.Entry<String, Object> entry : mapping.entrySet()) {
                //获取所有特定的字段 包括public private字段
                Field[] fields = entry.getValue().getClass().getDeclaredFields();
                for (Field field : fields) {
                    if (!field.isAnnotationPresent(XUAutowired.class))
                        continue;
                    else {
                        XUAutowired xuAutowired = field.getAnnotation(XUAutowired.class);
                        //接下来可能要使用qualifier注解了
                        if (!field.isAnnotationPresent(XUQualifier.class)) {
                            String beanName = xuAutowired.value().trim();
                            if ("".equals(beanName))
                                beanName = field.getType().getName();

                            //public 以外的修饰符 只要加了@XUAutowired 注解 都要强制赋值
                            //反射中叫做暴力访问，强吻
                            field.setAccessible(true);

                            try {
                                field.set(entry.getValue(), mapping.get(beanName));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            XUQualifier xuQualifier = field.getAnnotation(XUQualifier.class);
                            String qualifierName = xuQualifier.value().trim();
                            String beanName = xuAutowired.value().trim();
                            if ("".equals(qualifierName))
                                throw new RuntimeException("XUQualifier param value can not be empty");
                            else {
                                if ("".equals(beanName))
                                    beanName = field.getType().getName() + qualifierName;
                            }

                            //public 以外的修饰符 只要加了@XUAutowired 注解 都要强制赋值
                            //反射中叫做暴力访问，强吻
                            field.setAccessible(true);

                            try {
                                field.set(entry.getValue(), mapping.get(beanName));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    }
                }
            }
        }
    }

    //初始化url和Method的一对一对应关系
    private void initHandlerMapping() {
        if (mapping.isEmpty())
            return;
        for (Map.Entry<String, Object> stringObjectEntry : mapping.entrySet()) {
            Class clazz = stringObjectEntry.getValue().getClass();
            if (!clazz.isAnnotationPresent(XUController.class))
                continue;
            String baseUrl = "";
            if (clazz.isAnnotationPresent(XURequestMapping.class)) {
                XURequestMapping requestMapping = (XURequestMapping) clazz.getAnnotation(XURequestMapping.class);
                baseUrl = requestMapping.value();
            }

            Method[] methods = clazz.getMethods();

            for (Method method : methods) {
                if (!method.isAnnotationPresent(XURequestMapping.class))
                    continue;
                XURequestMapping requestMapping = method.getAnnotation(XURequestMapping.class);

                String url = (baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
                handlerMapping.put(url, method);

                System.out.println("Mapped " + url + "," + method);
            }
        }
        ;
    }

    private void doInstance() {
        //初始化 为DI做准备
        if (className.isEmpty()) {
            return;
        }
        try {
            for (String clazz : className) {
                Class clazzz = Class.forName(clazz);
                if (clazzz.isAnnotationPresent(XUController.class)) {
                    Object instance = clazzz.newInstance();
                    //将类名首字母小写
                    String beanName = clazzz.getName();
                    mapping.put(beanName, instance);
                } else if (clazzz.isAnnotationPresent(XUService.class)) {
                    //将类名首字母小写

                    XUService xuService = (XUService) clazzz.getAnnotation(XUService.class);
                    String beanName = xuService.value();
                    Object interfaces = clazzz.newInstance();


                    Class[] clazzzInterfaces = clazzz.getInterfaces();
                    //接下来是 实现接口的Service 配置进入ioc容器
                    if (clazzzInterfaces.length > 0) {
                        for (Class<?> i : clazzz.getInterfaces()) {
                            if (mapping.containsKey(i.getName())) {
                                throw new Exception("The beanName is exists!!");
                            }
//                            if (clazzz.isAnnotationPresent(XUTransactional.class)) {
//                                XUTransactional xuTransactional = (XUTransactional) clazzz.getAnnotation(XUTransactional.class);
//                                interfaces = this.getProxyObject(interfaces, true, true, xuTransactional.rollbackFor());
//                            } else {
//                                interfaces = this.getProxyObject(interfaces, true, false, null);
//                            }
                            //这里还需要判断这个service 有没有transactional 注解 因为时间有限 所以没有进行方法注解的判断 仅判断类注解有的话需要进行逻辑增强
                            if (!"".equals(beanName)) {


                                mapping.put(i.getName() + beanName, interfaces);
                            } else {
                                mapping.put(i.getName(), interfaces);
                            }


                        }
                    } else {
                        //判断service的value值
                        String keyName = "";
                        if (!"".equals(beanName)) {
                            keyName = beanName;
                        } else {
                            keyName = clazzz.getName();
                        }
                        //这里 将 所有没有实现接口的Service配置进入容器
                        if (mapping.containsKey(keyName)) {
                            throw new Exception("The beanName is exists!!");
                        }

//                        if (clazzz.isAnnotationPresent(XUTransactional.class)) {
//                            XUTransactional xuTransactional = (XUTransactional) clazzz.getAnnotation(XUTransactional.class);
//                            interfaces = this.getProxyObject(interfaces, false, true, xuTransactional.rollbackFor());
//                        } else {
//                            interfaces = this.getProxyObject(interfaces, false, false, null);
//                        }

                        mapping.put(keyName, interfaces);
                    }
                } else if (clazzz.isAnnotationPresent(XUReporsitory.class)) {
                    //将类名首字母小写

                    XUReporsitory xuReporsitory = (XUReporsitory) clazzz.getAnnotation(XUReporsitory.class);
                    String beanName = xuReporsitory.value();

                    Object interfaces = clazzz.newInstance();
                    for (Class<?> i : clazzz.getInterfaces()) {
                        if (mapping.containsKey(i.getName())) {
                            throw new Exception("The beanName is exists!!");
                        }

                        if (!"".equals(beanName)) {
                            beanName = toLowerFirstCase(clazzz.getSimpleName());
                            mapping.put(i.getName() + beanName, interfaces);
                        } else {
                            mapping.put(i.getName(), interfaces);
                        }

                    }
                } else if (clazzz.isAnnotationPresent(XUCompoment.class)) {
                    //将类名首字母小写

                    XUCompoment xuCompoment = (XUCompoment) clazzz.getAnnotation(XUCompoment.class);
                    String beanName = xuCompoment.value();
                    if ("".equals(beanName)) {
                        beanName = clazzz.getName();
                    }
                    if (mapping.containsKey(beanName)) {
                        throw new Exception("The beanName is exists!!");
                    }
                    //Compoment 作为顶级注解 只作用于没有任何接口的类
                    Object interfaces = clazzz.newInstance();
                    mapping.put(beanName, interfaces);
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String toLowerFirstCase(String simpleName) {

        char[] characters = simpleName.toCharArray();
        characters[0] += 32;
        return String.valueOf(characters);
    }

    private void doScanner(String scanPackage) {
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));

        assert url != null;
        File Path = new File(url.getFile());
        for (File file : Path.listFiles()) {
            if (file.isDirectory())
                doScanner(scanPackage + "." + file.getName());
            else {
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                String clazzName = (scanPackage + "." + file.getName().replace(".class", ""));
                className.add(clazzName);
            }
        }
    }

    //加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        //直接从类路径下找到spring主配置文件
        //并将其读取出来放入到properties属性中

        InputStream fis = null;
        fis = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            contextConfig.load(fis);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fis) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Object getProxyObject(final Object obj, Boolean interfaceFlag, final Boolean transactionalFlag, final Class[] exceptionClass) {
        //如果是实现过接口的标志,进行jdk增强
        if (interfaceFlag) {
            // 获取代理对象
            return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            Object result = null;

                            try {
                                if (transactionalFlag) {
                                    // 开启事务(关闭事务的自动提交)
                                    transactionManager.beginTransaction();
                                }

                                result = method.invoke(obj, args);

                                // 提交事务
                                if (transactionalFlag) {
                                    transactionManager.commit();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                // 回滚事务
                                if (transactionalFlag) {
                                    for (Class aClass : exceptionClass) {
                                        Object o = aClass.newInstance();
                                        if (e.getClass().isInstance(o)) {
                                            transactionManager.rollback();
                                            break;
                                        }
                                    }

                                }

                                // 抛出异常便于上层servlet捕获
                                throw e;

                            }

                            return result;
                        }
                    });
        } else {
            return Enhancer.create(obj.getClass(), new MethodInterceptor() {
                @Override
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                    Object result = null;
                    try {
                        // 开启事务(关闭事务的自动提交)
                        if (transactionalFlag) {
                            transactionManager.beginTransaction();
                        }

                        result = method.invoke(obj, objects);

                        // 提交事务
                        if (transactionalFlag) {
                            transactionManager.commit();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 回滚事务
                        if (transactionalFlag) {
                            if (transactionalFlag) {
                                for (Class aClass : exceptionClass) {
                                    Object object = aClass.newInstance();
                                    if (e.getClass().isInstance(object)) {
                                        transactionManager.rollback();
                                        break;
                                    }
                                }

                            }
                        }

                        // 抛出异常便于上层servlet捕获
                        throw e;

                    }
                    return result;
                }
            });
        }
    }

}
